﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using BCCommon;
using BCCommon.Enums;
using BCDto.UploadHandleComponent;
using BCDto.WeChatComponent.WeChatMediaRecord;
using BCService.WeChatComponent.WeChatMediaRecordService;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using WeChatSDK.Common.Enums.Material;
using WeChatSDK.WeChatDto.Material;
using WeChatSDK.WeChatDto.Request.Http;
using WeChatSDK.WeChatServiceComponent.Material;

namespace BCService.WeChatComponent.WeChatMaterialService.WeChatMaterialService
{
    /// <summary>
    /// 微信素材服务
    /// </summary>
    public class WeChatMaterialService : IWeChatMaterialService
    {
        private readonly IConfiguration configuration;
        private readonly IWeChatMediaRecordService weChatMedialRecordService;
        private readonly MaterialService materialService;

        public WeChatMaterialService(IConfiguration configuration,IWeChatMediaRecordService weChatMedialRecordService)
        {
            this.configuration = configuration;
            this.weChatMedialRecordService = weChatMedialRecordService;
            this.materialService = new MaterialService();
        }

        public string GetWeChatMaterialCount()
        {
            return WeChatHttpResponseHandle.ProcessMessage(this.materialService.GetPermanentMaterialCount());
        }
        public byte[] GetWeChatMaterialInfo(string mediaId, bool isPermanent)
        {
            return GetWeChatMaterialInfo(mediaId, isPermanent, false);
        }
        public byte[] GetWeChatMaterialInfo(string mediaId, bool isPermanent, bool isHD)
        {
            return WeChatHttpResponseHandle.ProcessData(this.materialService.GetMaterial(mediaId, isPermanent, isHD));
        }

        public string GetWeChatMaterialList(MaterialType materialType, int offset, int count)
        {
            return WeChatHttpResponseHandle.ProcessMessage(this.materialService.GetPermanentMaterialList(materialType, offset, count));
        }

        public void UploadTemporaryFileToWeChat()
        {
            IEnumerable<WeChatMediaRecordDto> weChatMediaRecordDtos = this.weChatMedialRecordService.UploadTemporaryFileToWeChat();
            foreach(WeChatMediaRecordDto dto in weChatMediaRecordDtos)
            {
                //TODO:还未完全实现
                //MaterialDto materialDto = new MaterialDto()
                //{
                //    FileType = dto.Type.ToString().ToLower(),
                //    FileSuffix = dto,
                //    FileName = uploadFileDto.FileName,
                //    FullFileName = uploadFileDto.FilePath
                //};
                //materialDto.VideoTitle = uploadFileDto.Remarks["material_title"].ToString();
                //materialDto.VideoDescription = uploadFileDto.Remarks["material_description"].ToString();
                //materialService.CheckContentLength(materialDto, isPermanent);
                //WeChatMediaType recordType = (WeChatMediaType)Enum.Parse(typeof(WeChatMediaType), (materialDto.FileType.Substring(0, 1).ToUpper() + materialDto.FileType.Substring(1)));
                //if (uploadFileDto.RemarkType == UploadFileRemarkType.WeChatPermanentThumbnailMaterial || uploadFileDto.RemarkType == UploadFileRemarkType.WeChatTemporaryThumbnailMaterial)
                //{
                //    recordType = WeChatMediaType.Thumb;
                //}
                //dynamic result = JsonConvert.DeserializeObject<dynamic>(WeChatHttpResponseHandle.ProcessMessage(this.materialService.UploadMaterial(materialDto, isPermanent)));
                //this.UploadWeChatMedial();
            }
        }

        public string UploadWeChatMedial(UploadFileDto uploadFileDto, bool isPermanent)
        {
            if (string.IsNullOrWhiteSpace(uploadFileDto.FileName))
            {
                throw new ArgumentException("文件名称不能为空。");
            }
            if (uploadFileDto.ContentLength <= 0)
            {
                throw new ArgumentException("文件内容不能为空。");
            }
            if (string.IsNullOrWhiteSpace(uploadFileDto.FileSuffix))
            {
                throw new ArgumentException("文件后缀不能为空。");
            }
            if (string.IsNullOrWhiteSpace(uploadFileDto.FilePath))
            {
                throw new ArgumentException("文件路径不能为空。");
            }
            if (!File.Exists(uploadFileDto.FilePath))
            {
                throw new ArgumentException("文件不存在。");
            }
            MaterialDto materialDto = new MaterialDto()
            {
                FileLength = uploadFileDto.ContentLength,
                FileType = uploadFileDto.FolderName,
                FileSuffix = uploadFileDto.FileSuffix,
                FileName = uploadFileDto.FileName,
                FullFileName = uploadFileDto.FilePath
            };
            materialDto.VideoTitle = uploadFileDto.Remarks["material_title"].ToString();
            materialDto.VideoDescription = uploadFileDto.Remarks["material_description"].ToString();
            materialService.CheckContentLength(materialDto, isPermanent);
            WeChatMediaType recordType = (WeChatMediaType)Enum.Parse(typeof(WeChatMediaType), (materialDto.FileType.Substring(0, 1).ToUpper() + materialDto.FileType.Substring(1)));
            if (uploadFileDto.RemarkType == UploadFileRemarkType.WeChatPermanentThumbnailMaterial || uploadFileDto.RemarkType == UploadFileRemarkType.WeChatTemporaryThumbnailMaterial)
            {
                recordType = WeChatMediaType.Thumb;
            }
            dynamic result = JsonConvert.DeserializeObject<dynamic>(WeChatHttpResponseHandle.ProcessMessage(this.materialService.UploadMaterial(materialDto, isPermanent)));
            WeChatMediaRecordDto weChatMediaRecordDto = new WeChatMediaRecordDto();
            weChatMediaRecordDto.CreateTime = DateTime.Now;
            weChatMediaRecordDto.CreatedAt = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            weChatMediaRecordDto.FileName = materialDto.FileName;
            weChatMediaRecordDto.IsTemporary = !isPermanent;
            weChatMediaRecordDto.MediaId = result.media_id;
            weChatMediaRecordDto.Type = recordType;
            weChatMediaRecordDto.Title = materialDto.VideoTitle;
            weChatMediaRecordDto.Description = materialDto.VideoDescription;
            if (weChatMediaRecordDto.Type != WeChatMediaType.News)
            {
                weChatMediaRecordDto.LocalUrl = string.Format("{0}/{1}", configuration["CurrentlyImageHost"],uploadFileDto.Src);
                if (!isPermanent)
                {
                    if (weChatMediaRecordDto.Type == WeChatMediaType.Thumb)
                    {
                        weChatMediaRecordDto.MediaId = result.thumb_media_id;
                    }
                    weChatMediaRecordDto.CreatedAt = result.created_at;
                    string type = result.type;
                    weChatMediaRecordDto.Type = (WeChatMediaType)Enum.Parse(typeof(WeChatMediaType), (type.Substring(0, 1).ToUpper() + type.Substring(1)));
                }
                else
                {
                    if (weChatMediaRecordDto.Type == WeChatMediaType.Image|| weChatMediaRecordDto.Type == WeChatMediaType.Thumb)
                    {
                        weChatMediaRecordDto.Url = result.url;
                    }
                }
            }
            this.weChatMedialRecordService.Add(weChatMediaRecordDto);
            if (recordType == WeChatMediaType.Thumb)
            {
                if (!isPermanent)
                {
                    return result.thumb_media_id;
                }
                else
                {
                    return result.media_id;
                }
            }
            else
            {
                return result.media_id;
            }
        }

        public void WeChatMaterialCheckData(UploadFileDto uploadFileDto)
        {
            bool isPermanent = false;
            if (uploadFileDto.RemarkType == UploadFileRemarkType.WeChatPermanentMaterial || uploadFileDto.RemarkType == UploadFileRemarkType.WeChatPermanentThumbnailMaterial)
            {
                isPermanent = true;
            }
            this.materialService.CheckContentLength(new MaterialDto()
            {
                FileLength = uploadFileDto.ContentLength,
                FileType = uploadFileDto.FolderName,
                FileSuffix = uploadFileDto.FileSuffix
            }, isPermanent);
        }
    }
}
